package com.demo.apparel.controller.uniapp;

import com.demo.apparel.common.Result;
import com.demo.apparel.entity.UserAddress;
import com.demo.apparel.service.uniapp.UserAddressService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/wx/address")
@Tag(name = "地址接口", description = "详细地址信息")
public class UserAddressController {

    @Autowired
    private UserAddressService addressService;

    /**
     * 新增地址
     * userId 通过拦截器或过滤器已经注入到 request attribute
     */
//    @PostMapping("/create")
//    public Result createAddress(@RequestBody UserAddress address,
//                                @RequestAttribute("userId") String userId) {
//        address.setUserId(userId);
//
//        // 如果设为默认地址，先取消已有默认
//        if (address.getIsDefault() != null && address.getIsDefault() == 1) {
//            addressService.unsetDefault(userId);
//        }
//
//        addressService.save(address);
//        return Result.success("保存成功");
//    }
//
//    /**
//     * 查询用户所有地址
//     */
//    @GetMapping("/list")
//    public Result listAddresses(@RequestAttribute("userId") String userId) {
//        List<UserAddress> list = addressService.listByUserId(userId);
//        return Result.success(list);
//    }

    // 新增地址
    @PostMapping("/create")
    public Result createAddress(@RequestBody UserAddress address,
                                @RequestAttribute("userId") String userId) {
        address.setUserId(userId);
        addressService.create(address);
        return Result.success("保存成功");
    }

    // 查询用户所有地址
    @GetMapping("/list")
    public Result listAddresses(@RequestAttribute("userId") String userId) {
        List<UserAddress> list = addressService.listByUserId(userId);
        return Result.success(list);
    }

    // 获取单条地址详情
    @GetMapping("/{id}")
    public Result getAddress(@PathVariable String id,
                             @RequestAttribute("userId") String userId) {
        UserAddress address = addressService.getById(id, userId);
        if (address == null) return Result.fail("地址不存在");
        return Result.success(address);
    }

    // 修改地址
    @PutMapping("/{id}")
    public Result updateAddress(@PathVariable String id,
                                @RequestBody UserAddress address,
                                @RequestAttribute("userId") String userId) {
        address.setId(id);
        address.setUserId(userId);
        addressService.saveOrUpdateDefault(address);
        return Result.success("更新成功");
    }

    // 删除地址
    @DeleteMapping("/{id}")
    public Result deleteAddress(@PathVariable String id,
                                @RequestAttribute("userId") String userId) {
        addressService.delete(id, userId);
        return Result.success("删除成功");
    }
}

